package at.nebbl.openscotty;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 * @author alex.nebel
 */
public class RequestHandler {

    private final String station = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><ReqC ver=\"1.1\" prod=\"String\" lang=\"DE\"><MLcReq><MLc n=\"<STATION>\" t=\"ST\" /></MLcReq></ReqC>";
    private final String url = "http://fahrplan.oebb.at/";
    private final String urlex = "bin/query.exe/dn";

    private OpenScottyStart act;

    //public RequestHandler(OpenScottyStart act) {
    //    this.act = act;
    //}

    public String requestStation(String station){
        try {
            InputStream in = doPost(url+urlex, createStationContent(station));
            BufferedReader baf = new BufferedReader(new InputStreamReader(in));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = baf.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        } catch (IOException ex) {
            
        }
        return "";
    }

    private String createStationContent(String station){
        String temp = this.station;
        return temp.replace("<STATION>", station);
    }
    
    private InputStream doPost(String urlString, String content) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        InputStream in = null;
        OutputStream out;
        byte[] buff;
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.connect();
        out = con.getOutputStream();
        buff = content.getBytes("UTF8");
        out.write(buff);
        out.flush();
        out.close();
        in = con.getInputStream();

        return in;
    }
}
